<script setup lang="ts">
import {
  NForm,
  NFormItem,
  NInput,
  NButton,
  type DataTableColumns,
  NDataTable,
  NSelect,
  useMessage,
  type SelectOption,
  NTreeSelect
} from 'naive-ui'
import { reactive, ref, onMounted, shallowRef } from 'vue'
import FixedAction from '@/components/FixedAction.vue'
import useRouteReplace from '@/hooks/useRouteReplace'
import { useRoute } from 'vue-router'
import type {
  DjBatchDetailModel,
  DjStat,
  CollectingDJTableRowModel,
  CommonSelectOptionModel
} from '@/api/batch'
import { sendRequest } from '@/utils/api'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'

const route = useRoute()
const message = useMessage()
const routeReplace = useRouteReplace(route.query.redirect as string)

const submitLoading = ref(false)
const handleSubmit = async () => {
  if (submitLoading.value) return

  if (checkedIds.value.length === 0) {
    message.error('请选择征集品')
    return
  }

  try {
    submitLoading.value = true
    const [error, res] = await sendRequest({
      module: 'batch',
      api: 'temporaryStorage',
      override: {
        data: {
          subItems: subItems.value
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    message.success(res.msg)
    routeReplace()
  } catch (error: any) {
    message.error(error.message)
  } finally {
    submitLoading.value = false
  }
}

const djBatchDetail = ref({} as DjBatchDetailModel)
const queryDjBatchDetail = async () => {
  try {
    const [error, res] = await sendRequest<HttpResponse<DjBatchDetailModel>>({
      module: 'batch',
      api: 'formInfo',
      override: {
        params: {
          batchId: route.params.id
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    djBatchDetail.value = res.data
  } catch (error) {
    console.error(error)
  }
}

const djStat = ref({} as DjStat)
const queryDjStat = async () => {
  try {
    const [error, res] = await sendRequest<HttpResponse<DjStat>>({
      module: 'batch',
      api: 'subitemStat',
      override: {
        params: {
          batchId: route.params.id
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    djStat.value = res.data
  } catch (error) {
    console.error(error)
  }
}

const djStatusOptions = shallowRef<CommonSelectOptionModel[]>([])
const djStatusLoading = ref(false)
const queryDjStatusOptions = async () => {
  try {
    djStatusLoading.value = true
    const [error, res] = await sendRequest<HttpResponse<CommonSelectOptionModel[]>>({
      module: 'batch',
      api: 'djStatusList'
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    djStatusOptions.value = res.data
  } catch (error) {
    console.log(error)
  } finally {
    djStatusLoading.value = false
  }
}

const subItemTypeOptions = shallowRef<any[]>([])
const subItemTypeLoading = ref(false)
const querySubItemTypeOptions = async () => {
  try {
    subItemTypeLoading.value = true
    const [error, res] = await sendRequest({
      module: 'collectProcess',
      api: 'listTreeAll',
      override: {
        params: {
          statusCode: 'A4901'
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    emptyChildrenToNull(res.data)
    subItemTypeOptions.value = res.data
  } catch (error) {
    console.log(error)
  } finally {
    subItemTypeLoading.value = false
  }
}
const emptyChildrenToNull = (e: any[]) => {
  for (const option of e) {
    if (option.childList && option.childList.length === 0) {
      option.childList = null
    }
    if (!option.childList) continue
    emptyChildrenToNull(option.childList)
  }
}

const formData = reactive({
  itemName: null,
  itemType: null,
  djStatus: null
})
const checkedIds = ref<number[]>([])
const subItems = shallowRef<CollectingDJTableRowModel[]>([])
const handleUpdateCheckedIds: any = (ids: number[], rows: CollectingDJTableRowModel[]) => {
  checkedIds.value = ids
  subItems.value = rows.filter((e) => !e.subItems)
}
const tableData = ref<CollectingDJTableRowModel[]>([])
const tableLoading = ref(false)

const columns: DataTableColumns<CollectingDJTableRowModel> = [
  {
    type: 'selection'
  },
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center',
    render: (e, index) => {
      if (!e.subItems) return null
      return index + 1
    }
  },
  {
    title: '征集品编码',
    key: 'subItemCode'
  },
  {
    title: '征集品名称',
    key: 'itemName'
  },
  {
    title: '所属线索',
    key: 'clueName'
  },
  {
    title: '类型',
    key: 'itemType'
  },
  {
    title: '征集方式',
    key: 'collectType'
  },
  {
    title: '点交状态',
    key: 'djStatus'
  }
]
const queryTableData = async () => {
  try {
    tableLoading.value = true
    const [error, res] = await sendRequest<HttpResponsePagination<CollectingDJTableRowModel>>({
      module: 'batch',
      api: 'collectingDJList',
      override: {
        params: {
          batchId: route.params.id,
          djStatusCode: formData.djStatus || null,
          itemName: formData.itemName || null,
          itemTypeCode: formData.itemType || null,
          limit: 10000000
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    res.data.list.forEach((e) => (e.subItemId = e.itemId))
    res.data.list.forEach((e) => (e.subItemCode = e.itemCode))
    tableData.value = res.data.list
    checkedIds.value = []
  } catch (error) {
    console.error(error)
  } finally {
    tableLoading.value = false
  }
}

onMounted(() => {
  Promise.allSettled([
    queryDjBatchDetail(),
    queryDjStat(),
    queryTableData(),
    queryDjStatusOptions(),
    querySubItemTypeOptions()
  ])
})
</script>

<template>
  <div class="dj-save">
    <div class="dj-save-title">批次信息</div>
    <NForm
      disabled
      label-placement="left"
      label-width="90rem"
      :show-feedback="false"
      class="dj-save-card grid"
    >
      <NFormItem label="批次编号：">
        <NInput
          placeholder="/"
          :value="djBatchDetail.batchCode"
        />
      </NFormItem>
      <NFormItem label="批次名称：">
        <NInput
          placeholder="/"
          :value="djBatchDetail.batchName"
        />
      </NFormItem>
      <NFormItem
        label="备注："
        style="grid-area: auto / span 2"
      >
        <NInput
          placeholder="/"
          type="textarea"
          rows="1"
          :value="djBatchDetail.description"
        />
      </NFormItem>
    </NForm>

    <div class="br"></div>

    <div class="dj-save-title">点交</div>
    <div class="dj-save-card dj-save-count">
      <div class="dj-save-count__item">
        <img src="@/assets/images/all-collection.png" />
        <span>
          <strong>{{ djStat.total }}</strong>
          件
        </span>
        <span>所有征集品</span>
      </div>
      <div class="dj-save-count__item">
        <img src="@/assets/images/djed.png" />
        <span>
          <strong>{{ djStat.clicked }}</strong>
          件
        </span>
        <span>已点交</span>
      </div>
      <div class="dj-save-count__item">
        <img src="@/assets/images/undj.png" />
        <span>
          <strong>{{ djStat.notClicked }}</strong>
          件
        </span>
        <span>未点交</span>
      </div>
      <div class="dj-save-count__item">
        <img src="@/assets/images/registered.png" />
        <span>
          <strong>{{ djStat.temporary }}</strong>
          件
        </span>
        <span>暂存</span>
      </div>
    </div>

    <div
      class="dj-save-card"
      style="padding: 0 20rem"
    >
      <NForm
        label-placement="left"
        :show-feedback="false"
        inline
        style="background-color: #ebeceb; padding: 15rem 20rem 20rem"
        @keydown.enter="queryTableData"
      >
        <NFormItem label="征集品名称：">
          <NInput
            v-model:value="formData.itemName"
            placeholder="请输入"
            clearable
          />
        </NFormItem>
        <NFormItem label="类型：">
          <NTreeSelect
            :loading="subItemTypeLoading"
            :options="subItemTypeOptions"
            children-field="childList"
            key-field="classificationCode"
            label-field="classificationName"
            v-model:value="formData.itemType"
            placeholder="请选择"
            clearable
            style="width: 150rem"
          />
        </NFormItem>
        <NFormItem label="点交状态：">
          <NSelect
            :loading="djStatusLoading"
            :options="(djStatusOptions as unknown as SelectOption[])"
            v-model:value="formData.djStatus"
            label-field="name"
            placeholder="请选择"
            clearable
            style="width: 150rem"
          />
        </NFormItem>
        <NFormItem>
          <NButton
            color="#5FB17F"
            ghost
            style="width: 100rem"
            @click="queryTableData"
          >
            查询
          </NButton>
        </NFormItem>
      </NForm>
    </div>

    <NDataTable
      :loading="tableLoading"
      :data="tableData"
      :columns="columns"
      children-key="subItems"
      :row-key="(row) => row.subItemId"
      :checked-row-keys="checkedIds"
      @update-checked-row-keys="handleUpdateCheckedIds"
      max-height="200rem"
      class="dj-save-card"
      style="padding-top: 0"
    />
  </div>

  <FixedAction>
    <div class="dj-save-buttons">
      <NButton
        color="#999999"
        ghost
        :disabled="submitLoading"
        @click="routeReplace"
      >
        取消
      </NButton>

      <NButton
        color="#5FB17F"
        :disabled="submitLoading"
        :loading="submitLoading"
        @click="handleSubmit"
      >
        确定
      </NButton>
    </div>
  </FixedAction>
</template>

<style scoped lang="scss">
.dj-save {
  min-height: 100%;
  padding: 15rem 0 110rem;
  background-color: #f0efee;

  :deep(.n-data-table__pagination) {
    justify-content: flex-start;
  }

  .br {
    position: relative;
    width: 100%;
    padding: 30rem 0;

    &::after {
      content: '';
      position: absolute;
      width: 100%;
      top: 50%;
      left: 0;
      border-top: 1px dotted #bc9e70;
      transform: translateY(-50%);
    }
  }

  .dj-save-card {
    padding: 20rem;
    background-color: #e1e1e1;
  }

  .n-form.grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16rem 60rem;
  }

  .dj-save-title {
    font-size: 26rem;
    margin-bottom: 30rem;
    color: #048c5e;
    line-height: 1;
  }

  .dj-save-count {
    display: flex;
    justify-content: center;
    gap: 0 16rem;
    background-color: #e1e1e1;

    &__item {
      display: grid;
      gap: 10rem 17rem;
      justify-content: center;
      grid-template-areas:
        'icon count'
        'icon label';
      flex: 1;
      padding: 18rem;
      background-color: #ebeceb;

      strong {
        font-size: 24rem;
      }

      img {
        display: block;
        grid-area: icon;
        width: 48rem;
        height: 48rem;
        margin-bottom: 10rem;
        align-self: end;
      }

      span:first-of-type {
        grid-area: count;
      }

      span:last-of-type {
        grid-area: label;
      }
    }
  }
}

.dj-save-buttons {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0 16rem;

  .n-button {
    width: 100rem;
    height: 50rem;
  }
}
</style>
